package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.EnterprisePersonRelation;
import model.UserAccount;
import util.Log;
import validator.PersonRelationValidator;
import web.JSONMessage;
import db.ImbiConnection;

public class PersonRelationController extends HttpServlet{

	private static final long serialVersionUID = 1L;
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		UserAccount u = (UserAccount) request.getSession().getAttribute("user");
		if(u != null){	
			if(request.getParameter("delete")!= null){
				delete(request, response);
			} else insert(request, response);
		}
	}
	
	private void delete(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try{
			int id = Integer.parseInt(request.getParameter("id"));			
			ImbiConnection.getEnterprisePersonRelationDAO().delete(new EnterprisePersonRelation(id, 0,0,0));
			response.getWriter().write(JSONMessage.message("Relation deleted"));
			Log.write(((UserAccount) request.getSession().getAttribute("user")).getUsername()+" relation "+id+" deleted ");	
		} catch(NumberFormatException e){
			response.getWriter().write(JSONMessage.errorMessage("Illegal parameters"));
		}				
	}
	
	private void insert(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		PersonRelationValidator validator = new PersonRelationValidator(
			request.getParameter("person"), 
			request.getParameter("relation_type"),
			request.getParameter("enterprise")			
		);
		
		if(validator.isValid()){
			EnterprisePersonRelation e = 
				new EnterprisePersonRelation(0, validator.getPerson(), validator.getEnterprise(), validator.getRelation());
			ImbiConnection.getEnterprisePersonRelationDAO().insert(e);
			response.getWriter().write(JSONMessage.message("New relation created!"));
			Log.write(((UserAccount) request.getSession().getAttribute("user")).getUsername()+" relation created between person "+e.getPerson()+" and enterprise "+e.getEnterprise());			
		}
		
		response.getWriter().write(JSONMessage.errorMessage("Invalid parameters"));
	}
}
